<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Paper extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this -> load -> model("Paper_model");
        $this -> load -> model("Paper_kh_model");
        $this -> load -> model("File_model");
        $this -> load -> model("Subject_model");
        $this -> load -> model("Author_model");
        $this -> load -> model("Journal_model");
        $this -> load -> model("User_model");
        $this->load->library('ProjectService/export_service');
        $this->load->library('ProjectService/upload_service');
        $this->load->library('ProjectService/audit_service');
        $this->load->library('ProjectService/check_service');
        $this -> sidebar = "Fruit";
    }

    public function Index()
    {
        $role=explode(',', getSess()['sub_role_id']);
        array_push($role, getSess()['role_id']);

        $data['is_add'] = 1;
        if (in_array(WebRole::BranchManage[XPHEnum::Value], $role) || in_array(WebRole::Sscientifictaff[XPHEnum::Value], $role)) {
            $data['is_add'] = 0;
        }
        $this -> load -> view('admin/paperList', $data);
    }

    public function getDatas($params = array(), $isExport = false)
    {
        $connar = array();
        $params = $_POST;
        if (!$isExport) {
            $connar = $this -> Paper_model -> pickPages($connar, $params);
        }

        $connar['orderby'] = "change_status desc, created desc";
        $connar['where']=$this->sqlEscape('is_del=?? ', array(CommonWhether::Not [XPHEnum::Value]));
        $connar['items']="db_paper.*,author.author,(case when status = '".ResultState::UnSubmit[XPHEnum::Value]."' THEN 0 when status = '".ResultState::Auditing[XPHEnum::Value]."' THEN 1 when status = '".ResultState::Publiced[XPHEnum::Value]."' THEN 3 when status = '".ResultState::Fail[XPHEnum::Value]."' THEN 99 END ) as change_status";
        $connar['join']=array('(select group_concat(db_author.author_name ORDER BY id ASC) author,data_id FROM db_author WHERE db_author.type = '.ResultsType::First[XPHEnum::Value].'  GROUP BY db_author.data_id ) author','author.data_id=db_paper.id');

        $role=explode(',', getSess()['sub_role_id']);
        array_push($role, getSess()['role_id']);

        $dept_name = getSess()['dept_name'];

        if (in_array(WebRole::BranchPresident[XPHEnum::Value], $role) || in_array(WebRole::BranchManage[XPHEnum::Value], $role)) {
            $connar['where'] .= $this->sqlEscape(' and dept_name=?? and status >?? ', array($dept_name,ResultState::UnSubmit [XPHEnum::Value]));
        } elseif (in_array(WebRole::Sscientifictaff[XPHEnum::Value], $role)) {
            $connar['where'] .= $this->sqlEscape('and status >?? ', array(ResultState::UnSubmit [XPHEnum::Value]));
        } elseif (in_array(WebRole::Teacher[XPHEnum::Value], $role)) {
            $connar['where'] .= $this->sqlEscape(' and (creator=?? ', array(getSess()['id']));
            $connar['where'] .= " or author.author like '%" . getSess()['username'] . "%' )";
        }

        if (isset($params['param'])) {
            $connar['where'] .= " and (name like '%" . $params['param'] . "%' )";
        }

        if(isset($params['audit_type']) && $params['audit_type']!='-1'){
            $connar['where'] .=$this->sqlEscape(" and is_submit_cg=??",array($params['audit_type']));
		}

        if (!$isExport) {
            $data = $this -> Paper_model -> get_page_list($connar);
            // echo $this->db->last_query();
        } else {
            $data["ret"] = $this -> Paper_model -> get_list_full($connar);
        }

        foreach ($data['ret'] as $k => $v) {
            $data['ret'][$k]['is_submit_cg_char'] = (new CommonWhether())->show($v['is_submit_cg']);
            if ($v['status'] == ResultState::UnSubmit [XPHEnum::Value] || $v['status'] == ResultState::Fail [XPHEnum::Value]) {
                $data['ret'][$k]['is_audit'] = true;
            } else {
                if($v['status'] == ResultState::Auditing [XPHEnum::Value]){
                    $data['ret'][$k]['is_audit'] = false;
                }else{
                    if(in_array(WebRole::Admin[XPHEnum::Value], $role) || in_array(WebRole::Manage[XPHEnum::Value], $role)){
                        $data['ret'][$k]['is_audit'] = true;
                    }else{
                        $data['ret'][$k]['is_audit'] = false;
                    }                 
                }   
            }
            if($v['creator'] == getSess()['id']){
                $data['ret'][$k]['is_edit'] = true;
            }else{
                $data['ret'][$k]['is_edit'] = false;
            }
        
            $data['ret'][$k]['status_char'] = (new ResultState())->show($v['status']);
            $data['ret'][$k]['is_cooperation'] = (new CommonWhether())->show($v['is_cooperation']);
            // $data['ret'][$k]['is_submit_kh_char'] = (new CommonWhether())->show($v['is_submit_kh']);
            $data['ret'][$k]['publish_time'] = $v['publish_time']?date('Y-m-d', $v['publish_time']):'--';
            $data['ret'][$k]['createdChar'] = $v['created']?date('Y-m-d H:i:s', $v['created']):'--';
            $data['ret'][$k]['status_char'] = (new ResultState())->show($v['status']);
			if($v['is_submit_kh'] == 0){
				$data['ret'][$k]['is_submit_kh_char'] = '未提交';
			}else{
				$data['ret'][$k]['is_submit_kh_char'] ='已提交';
			}
        }
        if (!$isExport) {
            echo json_encode($data);
        } else {
            //导出excel
            $new_list = array();	//需要导出的数据组
            foreach ($data["ret"] as $key => $value) {
                $new_list[$key]['xuhao'] = $key+1;//第一列序号
                $new_list[$key]['name'] = $value['name']; //论文题目
                $new_list[$key]['author'] = $value['author'];//所属作者
                $new_list[$key]['journal_name'] = $value['journal_name'];//刊物名称
                $new_list[$key]['journal_level'] = $value['journal_level'];//刊物级别
                $new_list[$key]['publish_time'] = $value['publish_time'];//发表日期
                $new_list[$key]['subject'] = $value['subject'];//学科门类
                $new_list[$key]['volume_number'] = $value['volume_number'];//卷号
                $new_list[$key]['issue_number'] = $value['issue_number'];//期号
                $new_list[$key]['page_range'] = $value['page_range'];//页码范围
                $new_list[$key]['words_number'] = $value['words_number'];//字数(千字)
                $new_list[$key]['cn'] = $value['cn'];//CN
                $new_list[$key]['issn'] = $value['issn'];//ISSN
                $new_list[$key]['journal_type'] = $value['journal_type'];//刊物发行类型
                $new_list[$key]['journal_range'] = $value['journal_range'];//刊物发表范围
                $new_list[$key]['is_cooperation'] = $value['is_cooperation'];//是否合作完成
                $new_list[$key]['school_rank'] = $value['school_rank'];//本校排名
                $new_list[$key]['personal_rank'] = $value['personal_rank'];//个人排名
                $new_list[$key]['type'] = $value['type'];//论文类型
                $new_list[$key]['dept_name'] = $value['dept_name'];//所属单位
                $new_list[$key]['performance_score'] = $value['performance_score'];//业绩分
                $new_list[$key]['bonus'] = $value['bonus'];			//奖金
                $new_list[$key]['createdChar'] = $value['createdChar'];//创建时间
            }
            //导出excel名称
            $name = '论文基本信息';

            //导出表头名称
            $tableth = '序号,论文题目,所属作者,刊物名称,刊物级别,发表日期,学科门类,卷号,期号,页码范围,字数(千字),CN,ISSN,刊物发行类型,刊物发表范围,是否合作完成,本校排名,个人排名,论文类型,所属单位,业绩分,奖金,创建时间';

            //new_list导出数据列,title 导出表名称,tableth表头名称

            $desc =  $this->export_service->export_excel($new_list, $name, $tableth, 2, 3, $name);

            //返回地址信息
            $director = $desc['director'];
            $file_name = $desc['file_name'];
            exit(retJson('返回地址', true, $director.$file_name));
        }
    }


    public function edit($id)
    {
        
        //是否合作完成
        $typelist =	array();
        foreach ((new CommonWhether())->getAll() as $k => $v) {
            $typelist[$k]['Value'] = $v[XPHEnum::Value];
            $typelist[$k]['Caption'] = $v[XPHEnum::Caption];
        }
        $data['typelist'] = $typelist;

        $sex_arr = array();
        foreach ((new CommonGender())->getAll() as $k => $v) {
            $sex_arr[$k]['Value'] = $v[XPHEnum::Value];
            $sex_arr[$k]['Caption'] = $v[XPHEnum::Caption];
        }
        $data['sex_arr'] = $sex_arr;

        //刊物级别
        $journal_level=array();
        foreach ((new JournalLevel())->getAll() as $k => $v) {
            $journal_level[$k]['Value'] = $v[XPHEnum::Value];
            $journal_level[$k]['Caption'] = $v[XPHEnum::Caption];
        }
        $data['journal_level_arr'] = $journal_level;

        //是否提交成果
		$is_submit_cg_arr =	array();
		foreach ((new CommonWhether())->getAll() as $k => $v) {
				$is_submit_cg_arr[$k]['Value'] = $v[XPHEnum::Value];
				$is_submit_cg_arr[$k]['Caption'] = $v[XPHEnum::Caption];
		}
		$data['is_submit_cg_arr'] = $is_submit_cg_arr;

        //$journal_type = '类型1,类型2,类型3,类型4,类型5,类型6';
        //$data['journal_type_arr'] = explode(",", $journal_type);
        // $data['examine_level_arr'] = array('国家级','省级','市级','校级','分院级'); 
        //考核等级
        $examine_level_arr=array();
        foreach ((new examine_level())->getAll() as $k => $v) {
            $examine_level_arr[$v[XPHEnum::Value]] = $v[XPHEnum::Caption];
        }
        $data['examine_level_arr'] = $examine_level_arr;

        //学科门类
        $subject_arr = $this->Subject_model->get_list(array());
        $data['subject_arr'] = array_column($subject_arr, 'name');

        //论文类型
        // $type = '中文核心,中文普通,SCI,EI期刊,EI会议,SSCI,其他';
        // $type = '中文核心,中文普通,SCI收录期刊,EI收录期刊,EI会议论文,SSCI收录期刊,SCI会议论文,顶级期刊 外文Science 和 Nature论文,权威期刊 外文Science 和 Nature子刊,A&HCI收录期刊,Scopus收录期刊,其他';
        $type_arr=array();
        foreach ((new PaperType())->getAll() as $k => $v) {
            $type_arr[$v[XPHEnum::Value]] = $v[XPHEnum::Caption];
        }
        $data['type_arr'] = $type_arr; //explode(",", $type);

        //教师/学生
        $data['subject']=$this->Subject_model->get_list(array());
        $identity_arr = array();
        foreach ((new CommonIdentity())->getAll() as $k => $v) {
            $identity_arr[$k]['Value'] = $v[XPHEnum::Value];
            $identity_arr[$k]['Caption'] = $v[XPHEnum::Caption];
        }
        $data['identity_arr'] = $identity_arr;


      
      
        
        
        $data['id'] = $id;
        if ($id == 0) {
            $data['title'] = "新增论文基本信息";
            $data['detail'] = $this -> Paper_model -> get_single(array("id" => $id));
            $data['can_audit'] = CommonWhether::Not[XPHEnum::Value];
            $data['can_save']=CommonWhether::Whether[XPHEnum::Value];
            $data['can_pass']=CommonWhether::Not[XPHEnum::Value];
            $data['can_refused']=CommonWhether::Not[XPHEnum::Value];

            $data['dept']=(new addDept)->getAllOneD();

        } else {
            $data['title'] = "编辑论文基本信息";

            $data['detail'] = $this -> Paper_model -> get_single(array("id" => $id));

            //2024年5月30号之前取之前旧的部门
            if($data['detail']['created'] < 1716998400){
                $data['dept']=(new Dept)->getAllOneD();
                foreach($data['dept'] as $k=>$v){
                    if($v == '机械工程分院' || $v== '电气电子工程分院'){
                        unset($data['dept'][$k]);
                    }
                }
            }else{
                $data['dept']=(new addDept)->getAllOneD();
            }

            $data['detail']['publish_time'] = $data['detail']['publish_time'] ? date("Y-m-d", $data['detail']['publish_time']) : '';

            $img = $this -> File_model -> get_list(array("data_id" => $data['detail']['id'],'type'=>ResultsType::First[XPHEnum::Value],'file_type'=>FileType::Img[XPHEnum::Value]));
            $data['detail']['img'] = $img;

            $files = $this -> File_model -> get_list(array("data_id" => $data['detail']['id'],'type'=>ResultsType::First[XPHEnum::Value],'file_type'=>FileType::File[XPHEnum::Value]));
            /*$data['detail']['filename'] = $files['src']?$files['src']:'';
            $data['detail']['file_id'] = $files['id'];
            if($files['src']){
                $new_name = explode("/",$files['src']);
                $data['detail']['new_filename'] = substr($new_name[3],8);;
            }else{
                $data['detail']['new_filename'] = '';
            }*/

            // 作者
            $connar['where']=$this->sqlEscape('db_author.data_id=?? and db_author.type=?? and db_user.is_del=0  ', array($id,ResultsType::First[XPHEnum::Value]));
            $connar['items']="db_author.*,db_user.id as author_id,db_user.usercode,db_user.username";
            $connar['join']=array('db_user','db_user.id=db_author.author_id and db_user.username=db_author.author_name');
            $connar1['groupby'] = "db_author.author_id";
            $connar['orderby'] = "db_author.id ASC";
            $data['author']=$this->Author_model->get_list_full($connar);
            // echo $this->db->last_query();
            // pri( $data['author']);

            // $data['author']=$this->Author_model->get_list(array('data_id'=>$id,'type'=>ResultsType::First[XPHEnum::Value]));
            
            foreach ($files as $k => $v) {
                $files[$k]['filename']= substr(explode("/", $v['src'])[3], 8);
            }
            $data['detail']['file']=$files;
            
            // 控制操作按钮
            if (isset($_GET['is_audit']) && isset($_GET['node']) && isset($_GET['state'])) {
                $role=explode(',', getSess()['sub_role_id']);
                array_push($role, getSess()['role_id']);

                // 当前操作为审核，若成果状态正确方可操作审核和保存
                $data['can_audit'] = CommonWhether::Not[XPHEnum::Value];
                if ($data['detail']['status']!=ResultState::Auditing[XPHEnum::Value]) {
                    if (in_array(WebRole::Sscientifictaff[XPHEnum::Value], $role) || in_array(WebRole::Admin[XPHEnum::Value], $role)) {
                        $data['can_save']=CommonWhether::Whether[XPHEnum::Value];
                        $data['can_pass']=CommonWhether::Not[XPHEnum::Value];
                        $data['can_refused']=CommonWhether::Not[XPHEnum::Value];
                    } else {
                        $data['can_save']=CommonWhether::Not[XPHEnum::Value];
                        $data['can_pass']=CommonWhether::Not[XPHEnum::Value];
                        $data['can_refused']=CommonWhether::Not[XPHEnum::Value];
                    }
                } else {
                    if (in_array(WebRole::BranchManage[XPHEnum::Value], $role) && $_GET['node']==AuditNode::Second[XPHEnum::Value] || $_GET['state'] == AuditState::Pass[XPHEnum::Value]) {
                        $data['can_save']=CommonWhether::Not[XPHEnum::Value];
                        $data['can_pass']=CommonWhether::Not[XPHEnum::Value];
                        $data['can_refused']=CommonWhether::Not[XPHEnum::Value];
                    } else {
                        $data['can_save']=CommonWhether::Whether[XPHEnum::Value];
                        $data['can_pass']=CommonWhether::Whether[XPHEnum::Value];
                        $data['can_refused']=CommonWhether::Whether[XPHEnum::Value];
                    }
                }
            } else {
                $role=explode(',', getSess()['sub_role_id']);
                array_push($role, getSess()['role_id']);
                $data['can_pass']=CommonWhether::Not[XPHEnum::Value];
                $data['can_refused']=CommonWhether::Not[XPHEnum::Value];
                // 当前操作为成果人，若成果状态正确方可保存提交
                if ($data['detail']['status']==ResultState::UnSubmit[XPHEnum::Value] || $data['detail']['status']==ResultState::Fail[XPHEnum::Value]) {
                    $data['can_save']=CommonWhether::Whether[XPHEnum::Value];
                    $data['can_audit']=CommonWhether::Not[XPHEnum::Value];
                } else {
                    if (in_array(WebRole::Admin[XPHEnum::Value], $role)) {
                        $data['can_save']=CommonWhether::Whether[XPHEnum::Value];
                    }else{
                        $data['can_save']=CommonWhether::Not[XPHEnum::Value];
                    }
               
                    $data['can_audit']=CommonWhether::Not[XPHEnum::Value];
                }
            }
        }


        


        $this -> load -> view('admin/paperEdit', $data);
    }



    public function save()
    {
        $param = $_POST;
        $save_type = $_POST['save_type'];
        unset($param['img']);
        unset($param['files']);
        unset($param['save_type']);

        unset($param['identity']);
        unset($param['author_name']);
        unset($param['author_id']);

        if (!isset($_POST['dept_name']) || $_POST['dept_name']=="-1") {
            exit(retJson('请选择所属部门', false));
        }
        if (!isset($_POST['subject']) || $_POST['subject']=="-1") {
            exit(retJson('请选择学科门类', false));
        }

        if (!isset($_POST['journal_level']) || $_POST['journal_level']=="-1") {
            exit(retJson('请选择刊物级别', false));
        }

        if (!isset($_POST['type']) || $_POST['type']=="-1") {
            exit(retJson('请选择论文类型', false));
        }

        if (!isset($_POST['identity']) || $_POST['identity']=="-1") {
            exit(retJson('请选择身份', false));
        }

        if (!isset($_POST['examine_level']) || $_POST['examine_level']=="-1") {
            exit(retJson('请选择等级', false));
        }

        if (!isset($_POST['is_submit_cg']) || $_POST['is_submit_cg']=="-1") {
            exit(retJson('请选择是否提交科研奖励', false));
        }

        //上传图片
        if (!isset($_POST['img']) || $_POST['img'] == '') {
            $param1=array();
        } else {

            // $_POST['img']=$this->NOTXSS_POST['img'];
            //    	//处理img
            //       if(checkStringIsBase64($_POST['img'])){
            //           $checkRet = uploadImg($_POST['img'],'paperImg');
            //           if(!$checkRet['status']){
            //               exit(toRetJson($checkRet));
            //           }
            //           $param1['src'] = $checkRet["v"];
            //       }else{
            //           $param1['src'] = $_POST['img'];
            //       }
            foreach ($_POST['img'] as $k => $v) {
                $param1[$k]['data_id']=$param['id'];
                ;
                $param1[$k]['src']=$v;
                $param1[$k]['type'] = ResultsType::First[XPHEnum::Value];
                $param1[$k]['file_type'] = FileType::Img[XPHEnum::Value];
                $param1[$k]['status'] = CommonStatus::UnDeleted [XPHEnum::Value];
                $param1[$k]['created'] = time();
            }
        }

        //上传文件

        if (!isset($_POST['files'])|| $_POST['files'] == '') {
            $param2=array();
        } else {
            foreach ($_POST['files'] as $k => $v) {
                $param2[$k]['data_id'] = $param['id'];
                ;
                $param2[$k]['src'] = $v;
                $param2[$k]['type'] = ResultsType::First[XPHEnum::Value];
                $param2[$k]['file_type'] = FileType::File[XPHEnum::Value];
                $param2[$k]['status'] = CommonStatus::UnDeleted [XPHEnum::Value];
                $param2[$k]['created'] = time();
            }
        }
        // 成果人信息
        foreach ($_POST['identity'] as $k => $v) {
            if ($_POST['identity'][$k]=='-1') {
                exit(retJson('请选择教师/学生/外校老师', false));
            }
            if ($_POST['author_name'][$k]=='') {
                exit(retJson('请输教师/学生/外校老师姓名', false));
            }

            $author[$k]['data_id']=$param['id'];
            $author[$k]['type']=ResultsType::First[XPHEnum::Value];
            $author[$k]['identity']=$_POST['identity'][$k];
            $author[$k]['author_id']=$_POST['author_id'][$k];
            $author[$k]['author_name']=$_POST['author_name'][$k];
            $author[$k]['created']=time();
        }


        //获取32位随机编码
        $get_only_code = $this->check_service->set_only_code(ResultsType::First[XPHEnum::Value],$_POST);
       

        if ($param['id'] == '0') {
            $names = $this -> Paper_model -> get_single(array('name'=>$param['name'],'is_del'=>CommonWhether::Not [XPHEnum::Value]));
            if ($names) {
                exit(retJson('论文题目已存在相同的，请注意', false));
            }
         
            $lls = $this -> Paper_model -> get_single(array('only_code'=> $get_only_code,'is_del'=>CommonWhether::Not [XPHEnum::Value]));
            if($lls){ //如果存在相同则重新获取32位编码
                $get_only_code = $this->check_service->set_only_code(ResultsType::First[XPHEnum::Value],$_POST);
            }
            //添加
            unset($param['id']);
            $param['publish_time'] = strtotime($param['publish_time']);
            $param['is_del'] = CommonWhether::Not [XPHEnum::Value];
            $param['creator'] = getSess()['id'];
            $param['created'] = time();
            $param['status'] = ResultState::UnSubmit[XPHEnum::Value];//成果状态
            $param['only_code'] = $get_only_code;
            //pri($param1);
            
            $id = $this -> Paper_model -> add($param);

            //保存图片
            foreach ($param1 as $k => $v) {
                $param1[$k]['data_id']=$id;
                $this -> File_model -> add($param1[$k]);
            }
            // $this -> File_model -> add($param1);

            // 文件保存
            foreach ($param2 as $k => $v) {
                $param2[$k]['data_id']=$id;
                $this -> File_model -> add($param2[$k]);
            }
            // $this -> File_model -> add($param2);

            // 保存作者
            foreach ($author as $k => $v) {
                $author[$k]['data_id']=$id;
                $this->Author_model->add($author[$k]);
            }
            //提交的时候新增审核记录
            if ($save_type  == 2) {
                $ress = $this->audit_service->addAudit(ResultsType::First[XPHEnum::Value], $id);
            }

            exit(retJson("添加成功.", true));
        } else {

            // var_dump( $param);
            
            //修改
            $param['only_code'] = $get_only_code;
            $param['publish_time'] = strtotime($param['publish_time']);

            $this -> Paper_model -> update($param);

            $imglist = $this -> File_model -> get_single(array("data_id" => $param['id'],'type'=>ResultsType::First[XPHEnum::Value],'file_type'=>FileType::Img[XPHEnum::Value]));
            /*if($imglist){
                //修改图片地址
                 $sql = "UPDATE `db_file` SET `src` = '".$param1['src']."'  WHERE data_id=".$param['id']." and type=".ResultsType::First[XPHEnum::Value]." and file_type=".FileType::Img[XPHEnum::Value].";";
                 $res = $this -> db ->query($sql);
            }else{
                //保存图片
                $param1['data_id'] =$param['id'];
                 $this -> File_model -> add($param1);

            }*/

            // 删除原有图片
            $this->File_model->delBatch($this->sqlEscape(" type=?? and data_id=?? and file_type=??", array(ResultsType::First[XPHEnum::Value],$param['id'],FileType::Img[XPHEnum::Value])));
            // 新增新图片
            foreach ($param1 as $k => $v) {
                $this -> File_model -> add($v);
            }

            /*$filelist = $this -> File_model -> get_single(array("data_id" => $param['id'],'type'=>ResultsType::First[XPHEnum::Value],'file_type'=>FileType::File[XPHEnum::Value]));
            if($filelist){
                    //修改文件地址
                 $sql1 = "UPDATE `db_file` SET `src` = '".$param2['src']."'  WHERE data_id=".$param['id']." and type=".ResultsType::First[XPHEnum::Value]." and file_type=".FileType::File[XPHEnum::Value].";";
                  $res1 = $this -> db ->query($sql1);
            }else{
                $param2['data_id'] = $param['id'];
                 $this -> File_model -> add($param2);

            }*/

            // 删除原有文件
            $this->File_model->delBatch($this->sqlEscape(" type=?? and data_id=?? and file_type=??", array(ResultsType::First[XPHEnum::Value],$param['id'],FileType::File[XPHEnum::Value])));
            // 新增新文件
            foreach ($param2 as $k => $v) {
                $this -> File_model -> add($v);
            }

            // 删除原有作者
            $this->Author_model->delBatch($this->sqlEscape(" type=?? and data_id=??", array(ResultsType::First[XPHEnum::Value],$param['id'])));
            // 新增新作者
            foreach ($author as $k => $v) {
                $this->Author_model->add($v);
            }

            //当状态已经审核通过后为已公开的时候,同步修改考核库的数据
            if($param['status'] ==  ResultState::Publiced[XPHEnum::Value]){
                $host_url = headerurl()."/"."zjipc_kycg/";
                $connar['join'][0]=array('(select group_concat(db_author.author_name  ORDER BY db_author.id ASC) author,group_concat( db_user.usercode ORDER BY db_author.id ASC ) authorcode,group_concat(db_author.identity  ORDER BY db_author.id ASC) identity,data_id FROM db_author left join db_user on db_user.id = db_author.author_id and db_user.username=db_author.author_name WHERE db_author.type = '.ResultsType::First[XPHEnum::Value].'  and db_user.is_del=0 GROUP BY db_author.data_id ) author','author.data_id=db_paper.id');
				$connar['join'][1]=array('(select group_concat(db_file.src ORDER BY db_file.id ASC separator \',\' ) AS imgurl, db_file.data_id AS img_data_id FROM db_file	WHERE ((db_file.type = '.ResultsType::First[XPHEnum::Value].' ) AND (db_file.file_type = '.FileType::Img[XPHEnum::Value].' )) GROUP BY db_file.data_id) img_view','img_view.img_data_id=db_paper.id');
				$connar['join'][2]=array('(select CONCAT(\''.$host_url .'\',group_concat(db_file.src ORDER BY db_file.id ASC SEPARATOR \','.$host_url.'\' )) AS fileurl, db_file.data_id AS file_data_id FROM db_file	WHERE ((db_file.type = '.ResultsType::First[XPHEnum::Value].' ) AND (db_file.file_type = '.FileType::File[XPHEnum::Value].')) GROUP BY db_file.data_id) file_view','file_view.file_data_id=db_paper.id');
				$connar['where'] = $this->sqlEscape('db_paper.id=?? ', array($param['id']));
				$data=$this->Paper_model->get_single_full($connar);
                $connar1['where'] = $this->sqlEscape('db_paper_kh.uuid=?? ', array('lw_'.$param['id']));
                // $connar1['where'] = "uuid ='lw_".$param['id']."'";
                $kh = $this->Paper_kh_model->get_single_full($connar1);
                if($kh){
                    unset($data['id']); unset($data['is_submit_kh']);unset($data['is_submit_cg']);unset($data['data_id']);unset($data['img_data_id']); unset($data['file_data_id']);  //移除考核表中不存在的字段
                    $data['id'] =$kh['id']; 
                    $data['publish_time'] = date("Y-m-d",$data['publish_time']);
                    $data['created'] = date("Y-m-d",$data['created']);
                    $this -> load -> model("Admin_model");
                    $admin = $this-> Admin_model -> get_single(array('id'=>$data['creator']));
                    $data['creator'] = $admin['username'];
                    $this->Paper_kh_model->update($data,'id'); //修改考核库
                }
            }

            //提交的时候新增审核记录
            if ($save_type  == 2) {
                $ress =  $this->audit_service->addAudit(ResultsType::First[XPHEnum::Value], $param['id']);
            }
            exit(retJson("修改成功.", true));
        }
    }

    

    //删除

    public function delete($id)
    {
        $list = $this -> Paper_model -> get_single(array("id" => $id));
        if ($list) {
            $param['id'] = $id;
            $param['is_del'] = CommonWhether::Whether [XPHEnum::Value];//已删除
            $this -> Paper_model -> update($param);
            $connar1['where'] = $this->sqlEscape('uuid=?? ', array('lw_'.$id));
            $kh = $this->Paper_kh_model->get_single_full($connar1);
            if($kh){
                $this->Paper_kh_model->update(array('id'=>$kh['id'],'is_del'=>CommonWhether::Whether[XPHEnum::Value]));
            }
           

        }
        exit(retJson("删除成功.", true));
    }


    //提交审核
    
    public function submit_audit($id)
    {
        $ress = $this->audit_service->addAudit(ResultsType::First[XPHEnum::Value], $id);

        if ($ress['status'] == true) {
            exit(retJson("操作成功.", true));
        }
    }

    // 审核列表
    public function auditView($id)
    {
        $data['audit']=$this->audit_service->auditProcess(ResultsType::First[XPHEnum::Value], $id);
        $this->load->view('admin/auditView', $data);
    }

    //获取刊物级别
    public function getJournalLevel()
    {
        $journal_name = $_POST['journal_name'];
        $publish_time = strtotime($_POST['publish_time']);

        if (isset($journal_name) && isset($publish_time) && $publish_time != "") {

            //查询数据库
            $sql = "SELECT type from db_journal where name='".$journal_name."' and if(end_time is null,UNIX_TIMESTAMP(start_time) <= ".$publish_time.",(UNIX_TIMESTAMP(start_time) <= ".$publish_time." AND UNIX_TIMESTAMP(end_time) >= ".$publish_time.")) ORDER BY FIELD(type,1,2,3,5,6,7,8,9,10) LIMIT 1;";
            $list = $this->Journal_model->query($sql);

            if($list){
                $type = $list[0]['type'];
            }else{
                $type = "";
            }       

             //北大核心不存在时刊物级别为其他
             if(!$type){
                 $type = JournalLevel::Fourth[XPHEnum::Value];
             }

             $data['type'] =  (new JournalLevel())->show($type);

             if($data['type'] == JournalLevel::Fourth[XPHEnum::Value]){
                if (isEnglish($journal_name)) {
                    $data['type'] =  $data['type'].'-英文';
                }else{
                    $data['type'] =  $data['type'].'-中文';
                }
             }
           

            echo json_encode($data);

        } else {
            echo json_encode(array('msg'=>'刊物名称或发表日期不能为空'));
        }
    }


    //获取刊物级别共同部分
    // function getConfigType($publish_time,$journal_name){

    //     $connar['where'] =$this->sqlEscape("name=?? and type=?? ", array($journal_name,JournalLevel::Second[XPHEnum::Value]));
    //     $list = $this -> Journal_model -> get_list_full($connar);
    //     $type = "";
    //     foreach ($list as $k => $v) {
    //         if ($v['end_time']) {
    //             if (strtotime($publish_time) >= strtotime($v['start_time']) && strtotime($publish_time) <= strtotime($v['end_time'])) {
    //                 $type = $v['type'];
    //             }
    //         } else {
    //             if (strtotime($publish_time) >= strtotime($v['start_time'])) {
    //                 $type = $v['type'];
    //             }
    //         }
    //     }
    //     return $type;
    // }



    // 导入
    public function importExcel()
    {
        if (!empty($_FILES)) {
            $pathlist  = $this->upload_service->UploadFile('paper', true); //上传文件
            $excellist = $this->export_service->importexcel($pathlist, 'Y', 'B', 3);

            $errer = array();
            foreach ($excellist as $key => $value) {
                $type = $value['D']=='教师' ? CommonIdentity::Teacher[XPHEnum::Value] : CommonIdentity::Student[XPHEnum::Value];
                $author = $this->User_model->get_single(array('username' => $value['C'], 'type' => $type));

                if (isset($author)) {
                    $param = array(
                        'name'              => $value['B'],
                        // 'author'            => $value['C'],
                        // 'identity'          => $value['D'],
                        'journal_name'      => $value['E'],
                        'journal_level'     => $value['F'],
                        'publish_time'      => $value['G'] ? PHPExcel_Shared_Date::ExcelToPHP($value['G']) : '',
                        'subject'           => $value['H'],
                        'volume_number'     => $value['I'],
                        'issue_number'      => $value['J'],
                        'page_range'        => $value['K'],
                        'words_number'      => $value['L'],
                        'cn'                => $value['M'],
                        'issn'              => $value['N'],
                        'journal_type'      => $value['O'],
                        'journal_range'     => $value['P'],
                        'is_cooperation'    => $value['Q']=='否' ? CommonWhether::Not[XPHEnum::Value] : CommonWhether::Whether[XPHEnum::Value],
                        'school_rank'       => $value['R'],
                        'personal_rank'     => $value['S'],
                        'type'              => $value['T'],
                        'subarea'           => $value['U'],
                        'performance_score' => $value['V'],
                        'bonus'             => $value['W'],
                        'dept_name'         => $value['X'],
                        'award_year'        => $value['Y'],
                        'created'           => time(),
                        'creator'           => getSess()['id'],
                        'status'            => ResultState::Publiced[XPHEnum::Value],
                        'is_del'            => CommonWhether::Not[XPHEnum::Value],
                    );
                    $id = $this->Paper_model->add($param);
                    $param1 = array(
                        'type'        => ResultsType::First[XPHEnum::Value],
                        'data_id'     => $id,
                        'identity'    => $type,
                        'author_id'   => $author['id'],
                        'author_name' => $value['C'],
                        'created'     => time(),
                    );
                    $this->Author_model->add($param1);
                } else {
                    $errer[] =  $key + 1;
                }
            }
			// pri($errer);exit();
            exit(retJson("导入成功", true, $errer));
        } else {
            exit(retJson("导入失败", false));
        }
    }


    //提交考核库

    // public function submit_kh($id){
    //     $ress = $this->check_service->addCheckDetail(ResultsType::First[XPHEnum::Value], $id);

    //     if ($ress['status'] == true) {
    //         exit(retJson("操作成功.", true));
    //     }
    // }


}
